import { Component, ElementRef, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd';
import { GoodsService } from '../../../../core/routes-services/goods.service';
import { SimpleEditorComponent } from '../../../../shared/simple-editor/simple-editor.component';
import { MyModalHelper } from '../../../../core/my-modal.helper';
import { GoodsClassService } from '../../../../core/routes-services/goods-class.service';
import { QCLOUD_DOMAIN, UPLOAD_DOMAIN } from '../../../../constant/config';
import { CacheService } from '../../../../core/routes-services/cache.service';

@Component({
  selector: 'app-step1',
  templateUrl: './step1.component.html',
  styles: [`
    :host ::ng-deep .ant-upload-select-picture-card {
      width: 128px;
      height: 128px;
    }

    :host ::ng-deep .ant-upload-select-picture-card i {
      font-size: 32px;
      color: #999;
    }

    :host ::ng-deep .ant-upload-select-picture-card .ant-upload-text {
      margin-top: 8px;
      color: #666;
    }

    :host ::ng-deep .ant-upload .avatar {
      width: 120px;
      height: 120px;
    }
  `],
})
export class Step1Component implements OnInit {
  entity: any = {};
  validateForm: FormGroup;
  goodsClassOptions: any [] = [];
  isLoading: boolean = false;
  uploadDomain = UPLOAD_DOMAIN;
  qcloudDomain = QCLOUD_DOMAIN;
  headers: any = {};
  componentDirty: boolean = false;
  @ViewChild('content') content: ElementRef;

  @Input() title: any;//商品名称
  @Output() titleChange = new EventEmitter();

  constructor(private router: Router,
              private modalHelper: MyModalHelper,
              private goodsClassService: GoodsClassService,
              public goodsService: GoodsService,
              private message: NzMessageService,
              private cacheService: CacheService,
              private fb: FormBuilder) {
  }

  ngOnInit() {
    const token: any = this.cacheService.getTokenInfo();
    this.headers = { 'Authorization': token };
    this.initClassOptions();
    this.entity = this.goodsService.entity;
    this.initValidateForm();
  }

  callbackTitle() {
    console.log(this.validateForm.controls.title.value);
  }


  initClassOptions() {
    this.goodsClassService.getAll().then((res) => {
      if (res.status.toString().startsWith('20')) {
        this.goodsClassOptions = res.data.goodsClassList;
      } else {
        this.message.warning(res.message);
      }
    }, error => {
      this.message.error(error.message ? error.message : error.error);
    });
  }

  initValidateForm() {
    this.entity.allowRetail = this.entity.allowRetail == 1 ? 1 : 2;
    this.validateForm = this.fb.group({
      title: [this.entity.title, [Validators.required, Validators.maxLength(60)]],
      price: [this.entity.price, [Validators.required]],
      classId: [this.entity.classId, [Validators.required]],
      stock: [this.entity.stock, [Validators.required]],
      // sortNum: [this.entity.sortNum, [Validators.required]],
      mainImg: [this.entity.mainImg, [Validators.required]],
      allowRetail: [this.entity.allowRetail, [Validators.required]],
      description: [this.entity.description, [Validators.required]],
    });
    this.content.nativeElement.innerHTML = this.entity.description ? this.entity.description : '点击进行内容编辑';
  }

  editorContent() {
    let description: any = this.entity.description;
    this.modalHelper.open(SimpleEditorComponent, { contentVal: description }, 800, {
      nzTitle: '编辑商品详情',
      nzMaskClosable: false,
    }).subscribe(content => {
      if (content) {
        this.entity.description = content;
        this.content.nativeElement.innerHTML = this.entity.description;
        this.componentDirty = true;
        this.validateForm.controls.description.setValue(content);
      }
    }, (error) => {
      console.error('弹窗回调出错：', error);
    });

  }

  isShow: boolean = false;

  showEdit() {
    this.isShow = !this.isShow;
    let body = document.body;
    if (this.isShow) {
      body.style.overflow = 'hidden';
      body.style.userSelect = 'none';
    } else {
      body.style.overflow = '';
      body.style.userSelect = '';
    }
  }

  contentCallback(content) {
    this.entity.description = content;
    this.content.nativeElement.innerHTML = this.entity.description;
    this.componentDirty = true;
    this.validateForm.controls.description.setValue(content);
  }

  submitForm() {
    let $this = this;
    if (this.validateForm.invalid) {
      for (const i in this.validateForm.controls) {
        this.validateForm.controls[i].markAsDirty();
        this.validateForm.controls[i].updateValueAndValidity();
      }
    } else {
      if (!this.entity.id || this.entity.id == 0) {
        //新增到最后一步再同一保存
        this.goodsService.entity = this.validateForm.value;
        this.title = this.goodsService.entity.title;
        this.titleChange.emit(this.title);
        ++this.goodsService.step;
      } else {
        //修改
        if (this.validateForm.dirty || this.componentDirty) {
          this.isLoading = true;
          this.goodsService.updateEntity(this.entity.id, this.validateForm.value).then((res) => {
            if (res.status.toString().startsWith('20')) {
              this.message.success('保存成功');
              this.entity = res.data;
              this.goodsService.entity = res.data;
              this.title = this.goodsService.entity.title;
              this.titleChange.emit(this.title);
              ++this.goodsService.step;
            } else {
              this.message.warning(res.message);
            }
            this.isLoading = false;
          }, error => {
            this.message.error(error.message ? error.message : error.error);
            this.isLoading = false;
          });
        } else {
          ++this.goodsService.step;
        }
      }
    }
  }

  /**
   * 上传图控件 ng-zorro upload
   *
   * @param {any} file
   * @param {any} fileList
   */
  handleChange({ file, fileList }): void {
    const status = file.status;
    if (status !== 'uploading') {
      // console.log(file, fileList);
    }
    if (status === 'done') {
      this.message.success(`${file.name} 上传成功`);
      let findIdx = fileList.findIndex(w => file.lastModified == w.lastModified);
      fileList[findIdx].imgKey = fileList[findIdx].response.data;
      fileList[findIdx].name = fileList[findIdx].response.data;
      fileList[findIdx].url = this.qcloudDomain + fileList[findIdx].response.data;
      this.entity.mainImg = fileList[findIdx].url;
      this.validateForm.controls.mainImg.setValue(this.entity.mainImg);
      this.componentDirty = true;
    } else if (status === 'error') {
      this.message.error(`${file.name} 上传失败`);
    }
  }

  goBack() {
    this.goodsService.reset();
    this.router.navigate(['/goods/list']);
  }
}
